<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'

import { useAddOrUpdateConfig, useChangeConfigEnable, useGetConfigItemList } from '@fl/api/man-api'
import { SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { tagBtns } from './constant'

const route = useRoute()
const { push } = useRouter()
const tableData = ref<any>([])

const showDiglog = ref(false)

const formState = {
    isEnabled: true,
    itemName: '',
    itemValue: '',
}
const form = ref<any>(cloneDeep(formState))

const gridOptions = reactive<any>({
    columns: [
        { fixed: 'left', title: '序号', type: 'seq', width: 50 },
        { field: 'itemName', title: '配置项名称' },
        { slots: { default: 'status' }, title: '启用状态' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },
    ],
    rowConfig: {
        keyField: 'id',
    },
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const params = computed(() => {
    return {
        pageNum: 1,
        pageSize: 999,
        parentId: route.query.parentId,
    }
})

const { data, isLoading, refetch } = useGetConfigItemList(params)
// 新增编辑表单配置
const formCol: any = [
    {
        fieldProps: {
            maxlength: 20,
        },
        label: '配置名称',
        prop: 'itemName',
    },
    {
        fieldProps: {
            maxlength: 300,
        },
        label: '配置值',
        prop: 'itemValue',
    },
    {
        label: '启用状态',
        prop: 'isEnabled',
        valueType: 'switch',
    },
]
function validateName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入配置名称'))
    }
    if (pattern.test(value))
        callback(new Error('配置名称不允许输入空格'))

    else
        callback()
}
function validateValue(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入配置值'))
    }
    if (pattern.test(value))
        callback(new Error('请输入配置值不允许输入空格'))

    else
        callback()
}
const rules = {
    itemName: [{ required: true, trigger: 'blur', validator: validateName }],
    itemValue: [{ required: true, trigger: 'blur', validator: validateValue }],
}

const { mutate: addOrUpdateMutate } = useAddOrUpdateConfig()

const { mutate: changeStatusMutate } = useChangeConfigEnable()
function doAction(item: any, row: any) {
    switch (item.value) {
        case 'edit':
            const obj = {
                ...row,
                isEnabled: row.isEnabled === 0,
            }
            form.value = cloneDeep(obj)
            showDiglog.value = true
            break

        default:
            break
    }
}

function doAdd() {
    form.value = cloneDeep(formState)
    form.value.parentId = params.value.parentId
    showDiglog.value = true
}

function doSave() {
    const params = {
        ...form.value,
        isEnabled: form.value.isEnabled ? 0 : -1,
        multipleChoice: 0,
    }
    addOrUpdateMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            showDiglog.value = false
            refetch()
        },
    })
}
function changeStatus(row: any) {
    const params = {
        id: row.id,
        isEnabled: row.isEnabled === 0 ? -1 : 0,
    }
    changeStatusMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
        },
    })
}

watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value?.rows) ?? []
    }
})
</script>

<template>
    <ElCard shadow="never">
        <div class="mb-20 cursor-pointer"
             @click="() => push('/operations-pages/system-setting/system-configuration')"
        >
            <div i-radix-icons:double-arrow-left
                 class="text-red size-16"
            />
            返回
        </div>

        <SearchTable v-loading="isLoading"
                     v-bind="gridOptions"
                     :data="tableData"
        >
            <template #toolbar_buttons>
                <ElButton type="primary"
                          @click="doAdd"
                >
                    新增配置项
                </ElButton>
            </template>

            <template #status="{ row }">
                <vxe-switch :model-value="row.isEnabled === 0"
                            @change="changeStatus(row)"
                />
            </template>

            <template #operate="{ row }">
                <ButtonItem :btns="tagBtns"
                            @btn-click="doAction($event, row)"
                />
            </template>
        </SearchTable>
    </ElCard>

    <PlusDialogForm v-model:visible="showDiglog"
                    v-model="form"
                    :title="form?.dictCode ? '编辑' : '新增'"
                    :form="{ columns: formCol, rules, labelWidth: 100, labelPosition: 'top' }"
                    @confirm="doSave"
    />
</template>

<style lang="scss" scoped></style>
